package cn.tedu.reflection;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class TestReflect {
    @Test
    public void getClazz() throws ClassNotFoundException {
        Class<?> clazz1 = Class.forName("cn.tedu.reflection.Student");
        Class<?> clazz2 = Student.class;
        Class<?> clazz3 =new Student().getClass();

        System.out.println(clazz1);//class cn.tedu.reflection.Student
        System.out.println(clazz1.getName());//cn.tedu.reflection.Student
        System.out.println(clazz1.getSimpleName());//Student
        //获取Student类对应的包对象
        System.out.println(clazz1.getPackage());//package cn.tedu.reflection
        System.out.println(clazz1.getPackage().getName());//cn.tedu.reflection

     }
     @Test
     public void getFie() throws ClassNotFoundException {
         Class<?> clazz = Class.forName("cn.tedu.reflection.Student");
         Field[] fs = clazz.getFields();
         //System.out.println(Arrays.toString(fs));
         for(Field f:fs){
             /*注意!目前成员变量的修饰类似需要是public才能获取到,
             其他修饰符可以通过暴力反射获取*/
             System.out.println(f);
             System.out.println(f.getName());
             System.out.println(f.getType());
         }
     }
     @Test
     public void getFuction(){
         Class<?> clazz = Student.class;
         Method[] ms = clazz.getMethods();
         System.out.println(Arrays.toString(ms));
         for (Method m:ms){
             System.out.println(m.getName());
             System.out.println(Arrays.toString(m.getParameterTypes()));

         }
     }
     @Test
     public void getCons(){
         Class<?> clazz = Student.class;
         Constructor[] cons = clazz.getConstructors();
         System.out.println(Arrays.toString(cons));
         for(Constructor c:cons){
             System.out.println(c.getName());
             System.out.println(Arrays.toString(c.getParameterTypes()));
         }
     }
    @Test
    public void getObject() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> clazz = Student.class;
        //.newInstance()触发无参构造创建对象
        Object o = clazz.newInstance();
        System.out.println(o);

        /*反射创建对象方案2:触发目标类的全参构造创建对象
        * 1.先获取指定的构造函数对象,
        * 注意需要指定构造函数的参数,并且传入的是.class字节码对象
        * */
        Constructor<?> c = clazz.getConstructor(String.class,int.class);
        System.out.println(c);
        Object o2 = c.newInstance("赵六", 6);
        System.out.println(o2);

        Constructor<?> c1 = clazz.getConstructor(String.class, int.class, int.class);
        System.out.println(c1);
        Object o3 = c1.newInstance("王五", 8, 9);
        System.out.println(o3);
    }



}
